package com.xh.petdogexpert.sys.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xh.petdogexpert.base.BaseException;
import com.xh.petdogexpert.sys.dto.Resource;
import com.xh.petdogexpert.sys.mapper.ResourceMapper;
import com.xh.petdogexpert.sys.service.IResourceService;

@Transactional
@Service
public class ResourceServiceImp implements IResourceService {

	@Autowired
	ResourceMapper resourceMapper;

	@Override
	public int deleteResource(Resource resource) throws BaseException {
		try {
			resourceMapper.deleteResource(resource);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("删除资源出错");
		}
		return 0;
	}

	@Override
	public List<Resource> queryResources(Resource resource) {

		List<Resource> resources = resourceMapper.queryResources(resource);
		return resources;
	}
	
	@Override
	public List<Resource> makeTree(List<Resource> resources) {
		for (Resource i : resources) {
			for (Resource j : resources) {
				if (i.getId() == j.getPid()) {
					if (i.getChildren() == null)
						i.setChildren(new ArrayList<Resource>());
					i.getChildren().add(j);
				}
			}
		}
		resources.removeIf((Resource r) -> {
			if (r.getPid() != 0)
				return true;
			else
				return false;
		});
		return resources;
	}
	
	@Override
	public List<Resource> queryResourcesTree(Resource resource) {
		List<Resource> resources = queryResources(resource);
		return makeTree(resources);
	}

	@Override
	public Resource getResource(Resource resource) throws BaseException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Integer updateResource(Resource resource) throws BaseException {
		Integer id;
		try {
			id = resourceMapper.updateResource(resource);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("更新失败");
		}
		return id;
	}

	@Override
	public Integer addResource(Resource resource) throws BaseException {
		try {
			resourceMapper.addResource(resource);
			return resource.getId();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("新增失败");
		}

	}

}
